import os, sys
try:
  from PyPDF2 import PdfWriter, PdfReader
except:
  os.system("pip3 install --user pyPdf2")
  from PyPDF2 import PdfWriter, PdfReader

def main(a2_width=450, a3_offset=10, a4_offsetSkip=0, a5_height=600, a1=""):
  if not os.path.exists("outputs"):
    os.mkdir("outputs")
  f = PdfReader(open(a1, "rb"), strict=False)
  f2 = PdfWriter()
  f_name = os.path.basename(a1)
  for i, page in enumerate(f.pages):

    v = page.cropbox.upper_right
    if i<= a4_offsetSkip:
      offset = 0
    else:
      offset = a3_offset*(i%2*2-1)
    v3= (v[0]-a2_width)//2+offset
    v4= (v[0]+a2_width)//2+offset
    upper = float(v[1]) / 2 + a5_height / 2
    if upper > v[1]:
      upper = v[1]
    lower = float(v[1]) / 2 - a5_height / 2
    if lower < 0:
      lower = 0
    print(upper, lower)
    page.mediabox.upper_left = (v3, upper)
    page.mediabox.upper_right = (v4, upper)
    page.mediabox.lower_left = (v3, lower)
    page.mediabox.lower_right = (v4, lower)
    f2.add_page(page)

  f2.write(open(os.path.join("outputs" ,f_name), 'wb'))


if __name__ == "__main__":
  if len(sys.argv[1:])==1:
    main(sys.argv[1])
    print("width=450, offset=10, offsetSkip=0, height=600, ...")
  elif len(sys.argv[1:])>=4:
    print("width=%s, offset=%s, offsetSkip=%s, height=%s, ..." %(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]))
    for i in sys.argv[5:]:
      main(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]), i)
  else:
    print("width=450, offset=10, offsetSkip=0, height=600, ...")
